package xiaopiya.robot.handler;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;


/**
 * 抽象命令处理
 * 
 * @author Ray (ayufox@gmail.com)
 * @version 0.1
 */
public abstract class AbstractMessageHandler implements IMessageHandler
{
	protected final Log LOG = LogFactory.getLog(getClass());

	/* (non-Javadoc)
	 * @see xiaopiya.robot.handler.IMessageHandler#handle(org.jivesoftware.smack.XMPPConnection, org.jivesoftware.smack.Chat, org.jivesoftware.smack.packet.Message, java.lang.String)
	 */
	public void handle(XMPPConnection connection, Chat chat, Message message, String body)
			throws XMPPException
	{
		try
		{
			String from = message.getFrom().split("/")[0];
			String result = handle(from, body);
			if (LOG.isInfoEnabled())
			{
				LOG.info("request:[" + message.getBody() + "]result:[" + result + "] from [" + chat.getParticipant() + "]：" + connection.getUser());
			}
			chat.sendMessage(result);
		} catch (Throwable t)
		{
			LOG.error("error", t);
			chat.sendMessage("系统错误，请稍后重试");
		}
	}
	
	protected abstract String handle(String from, String params) throws Exception;
}
